package structure;

import java.util.Iterator;
import java.util.NoSuchElementException;

public class Stack implements Iterable{

    private final int SIZE = 10;
    
    private char[] elements;
    private int top;
    
    public Stack() {
        elements = new char[SIZE];
        top = -1;
    }
    
    public Stack(int capacity) {
        elements = new char[capacity];
        top = -1;
    }
    
    public void push(char element) {
        if (top >= SIZE) {
            throw new IndexOutOfBoundsException("Stack overflow");
        }
        elements[++top] = element;
    }
    
    public char peek(){
        if (isEmpty()) {
            throw new NoSuchElementException("Stack underflow");
        }
        return elements[top];
    }
    
    public char pop(){
        if (isEmpty()) {
            throw new NoSuchElementException("Stack underflow");
        }
        return elements[top--];
    }
    
    public boolean isEmpty() {
        return top == -1;
    }
    
    public int size() {
        return elements.length;
    }
    
    public Iterator  iterator() {
        return new Iter();
    }
    
    private class Iter implements Iterator{

        @Override
        public boolean hasNext() {
            return top != -1;
        }

        @Override
        public Character next() {
            if (hasNext()) {
                return elements[top--];
            }
            return (Character) null;
        }

        @Override
        public void remove() {
            if (hasNext()) {
                top--;
            } 
        }
    }
}
